package com.flamingo.xiaomiweather.logic;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.flamingo.xiaomiweather.common.Result;
import com.flamingo.xiaomiweather.logic.model.PlaceResponse;
import com.flamingo.xiaomiweather.logic.network.XiaomiWeatherNetwork;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 这个方法是对请求的封装，用来处理status状态是否请求成功，如果失败也需要包装一层再返回
 */
public class Repository {

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    public LiveData<Result<PlaceResponse>> searchPlaces(final String query) {
        final MutableLiveData<Result<PlaceResponse>> resultLiveData = new MutableLiveData<>();
        executorService.execute(() -> {
            try {
                XiaomiWeatherNetwork xiaomiWeatherNetwork = new XiaomiWeatherNetwork();
                PlaceResponse placeResponse = xiaomiWeatherNetwork.searchPlaces(query).get();
                if ("ok".equals(placeResponse.getStatus())) {
                    resultLiveData.postValue(Result.success(placeResponse));
                } else {
                    resultLiveData.postValue(Result.failure(new RuntimeException("response status is " + placeResponse.getStatus())));
                }
            } catch (Exception e) {
                resultLiveData.postValue(Result.failure(e));
            }
        });

        return resultLiveData;
    }

}
